import React, { useLayoutEffect, useState } from "react";
import { useRequest } from "ahooks";

const fetchData = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ text: "文本内容" });
    }, 3000);
  });
};

const determineUserResponseTime = (diffTime) => {
  if (diffTime >= 0 && diffTime <= 16) {
    return 1;
  }
  if (diffTime > 16 && diffTime <= 100) {
    return 2;
  }
  if (diffTime > 100 && diffTime <= 1000) {
    return 3;
  }
  if (diffTime > 1000 && diffTime <= 10000) {
    return 4;
  }
  return 5;
};

const useEventPerformance = () => {
  let startTime = 0;
  let endTime = 0;
  let diffTime = 0;
  let rICId = -1;

  const [stage, setStage] = useState(1);
  const start = () => {
    startTime = performance.now();
    console.log("startTime", startTime);
    calculateTimeDifference();
  };

  const end = () => {
    endTime = performance.now();
    cancelIdleCallback(rICId);
    console.log("时间差为：", endTime - startTime);
  };

  const calculateTimeDifference = () => {
    rICId = requestIdleCallback(() => {
      console.log("requestIdleCallback");

      cancelIdleCallback(rICId);
      const now = performance.now();
      diffTime = now - startTime;
      setStage(determineUserResponseTime(diffTime));
      calculateTimeDifference();
    });
  };

  return [start, end, stage, diffTime];
};

const Button = () => {
  const { data, error, loading, runAsync } = useRequest(fetchData, { manual: true });

  console.log(data, error, loading);

  const [start, end, stage, diffTime] = useEventPerformance();

  console.log("stage", stage);

  return (
    <div>
      <div>diffTime: {diffTime}</div>
      {stage >= 3 ? <div>loading......</div> : null}
      <div
        onClick={async () => {
          start();
          await runAsync();
          end();
        }}
      >
        {data?.text || "占位符"}
      </div>
    </div>
  );
};

export default Button;


预取数据
骨架屏  mount 
事件 update